package com.xopencode.file;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;

/**
 * @Auther: Mcb
 * @Date: 2021/6/11 14:23
 * @Description:
 */
public class FileUtil {


    /**
     * 场景：将数据拼接成一行，放在txt文本文件中，以表单的形式对文件进行发送
     * @param request
     * @return java.lang.String
     * @description 获取入参文件数据（只获取一行）
     **/
    public static String getSingleParamBytes(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        Iterator<String> fileNames = params.getFileNames();
        if (fileNames.hasNext()) {
            MultipartFile file = params.getFile(fileNames.next());
            return new String(file.getBytes());
        }
        return null;
    }

    /**
     * 获取入参文件数据
     * @param request
     * @return
     * @throws Exception
     */
    public static byte[] getParamBytes(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        Iterator<String> fileNames = params.getFileNames();
        if (fileNames.hasNext()) {
            MultipartFile file = params.getFile(fileNames.next());
            return file.getBytes();
        }
        return null;
    }

}
